package com.ly.controller;

import com.ly.pojo.SysDept;
import com.ly.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.util.List;

@Controller
@RequestMapping("/dept")
//@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;
    private String prefix = "dept/";

    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(required = false) SysDept sysDept,
                       @RequestParam(defaultValue = "1", required = false) Integer pageNo) {
        //页面大小
        Integer pageSize = 3;

        List<SysDept> list = deptService.getPaging(sysDept, pageNo, pageSize);

        //总记录数
        Integer totalCount = deptService.getCount(sysDept);
        //总页数
        Integer totalPages = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPages++;
        }


        model.addAttribute("list", list);
        model.addAttribute("sysDept", sysDept);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);

        return prefix + "list";//转发
    }


    /**
     * 新增
     * @param returnPerson
     * @return
     */
    @PostMapping("/add")
    public String add(SysDept sysDept){
        Integer add = deptService.add(sysDept);

        if (add>0){
            return "redirect:list";//重定向
        }

        return prefix + "add";
    }

    @GetMapping("/add")
    public String add(){
        return "add";
    }



    /**
     * 查询单条记录
     * @param model
     * @param id
     * @return
     * @throws ParseException
     */
    @GetMapping("/byId")
    public String byId(Model model,Integer id) throws ParseException {
        SysDept sysDept = deptService.getById(id);
        model.addAttribute("sysDept",sysDept);
        return "update";
    }


    /**
     * 更新
     * @param returnPerson
     * @return
     */
    @PostMapping("/update")
    public String update(SysDept sysDept) {
        Integer update = deptService.update(sysDept);
        if (update>0){
            return "redirect:list";//重定向
        }
        return "update";
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public String delete(Integer id){
        Integer delete = deptService.delete(id);

        if (delete>0){
            return "redirect:list";//重定向
        }

        return "list";
    }
}
